<template>
  <el-dialog title="审核" :visible.sync="openAuth" width="500px" :append-to-body="true" :close-on-click-modal="false" @close="onDialogClose">
      <el-form ref="codeForm" :model="authForm" @submit.native.prevent :rules="rules" label-width="80px">
        <el-form-item label="" label-width="20px">
          <span>{{ title }}</span>
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <div class="code-input">
            <el-input v-model.trim="authForm.code" maxlenth="6"></el-input>
              <div class="coding">
                <span v-if="checking=='checking'">{{ codeTime }}s后再试</span>
                <el-button v-else-if="checking=='wait'" type="text" class="get-code" @click="getCode">发送</el-button>
                <el-button v-else class="get-code" type="text" @click="getCode">重新发送</el-button>
              </div>
            </div>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button type="primary" :loading="loading" @click="submit">确 定</el-button>
        <el-button @click="openAuth = false">取 消</el-button>
      </div>
    </el-dialog>
</template>
<script type="text/javascript">
import { sendCode } from '@/api/member/product'
export default {
  name: 'AuthCode',
  props: {
    title: String,
    visible: Boolean,
    authObj: {
      type: Object,
      default: () => ({})
    }
  },
  data () {
    return {
      code: '',
      codeTime: 0,
      checking: 'wait',
      loading: false,
      authForm: {
        code: ''
      },
      rules: {
        code: { required: true, message: '验证码不能为空', trigger: 'blur' }
      }
    }
  },
  computed: {
    openAuth: {
      get () {
        return this.visible
      },
      set (val) {
        this.$emit('update:visible', val)
      }
    }
  },
  methods: {
    getCode () {
      sendCode(this.authObj).then(res => {
        this.vid = res.data.vid
        this.timeChange()
      })
    },
    timeChange () {
      this.checking = 'checking'
      this.codeTime = 60
      clearInterval(this.timerId)
      this.timerId = setInterval(() => {
        this.codeTime--
        if (this.codeTime <= 0) {
          clearInterval(this.timerId)
          this.codeTime = 0
          this.checking = 'timeout'
        }
      }, 1000)
    },
    onDialogClose () {
      this.resetForm('codeForm')
      clearInterval(this.timerId)
      this.checking = 'wait'
      this.loading = false
    },
    submit () {
      this.$refs.codeForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$emit('submit', {
            code: this.authForm.code,
            vid: this.vid
          })
        }
      })
    },
    cancelLoading () {
      this.loading = false
    }
  }
}
</script>
<style lang="scss" scoped>
.code-input{
  position: relative;
}
.coding{
  position: absolute;
    right: 0;
    top: 0;
    padding-right: 20px;
}
</style>
